package com.smart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smart.entity.LoginUser;
import com.smart.entity.Users;
import com.smart.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 重写框架的 UserDetailsService 的 loadUserByUsername 方法
 * 从数据库中查询用户信息
 * 因为原框架的内用信息是存在内存中的
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Users users = userMapper.selectOne(queryWrapper);
//        如果没有查询到用户，抛出异常
        if (Objects.isNull(users)) {
            System.out.println("12345678910");
            throw new RuntimeException("用户名或者密码错误！");
        }
        return new LoginUser(users);
    }
}

